package com.godot.service;

import java.io.BufferedOutputStream;
import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.godot.protocol.ReqCode;
import com.godot.util.Constants;
import com.godot.util.Log;
import com.godot.util.PMF;

public abstract class Service extends BaseService implements ReqCode {
	
	protected int _action;
	protected HttpServletRequest _req;
	protected HttpServletResponse _resp;
	protected PersistenceManager _pm;
	protected HttpSession _session;
	
	public Service init(HttpServletRequest req, HttpServletResponse resp) {
		Log.info("Action : " + req.getParameter(kAttrAction));
		Log.info("Content : " + req.getParameter(kAttrContent));
		
		_action = Integer.parseInt(req.getParameter(kAttrAction));
		_req = req;
		_resp = resp;
		_session = req.getSession();
		
		return this;
	}

	protected void writeResp(String theRespStr) throws IOException {
		BufferedOutputStream out = new BufferedOutputStream(_resp.getOutputStream());
		out.write(theRespStr.getBytes(Constants.kStringUTF8EnCoding));
		out.flush();
		out.close();
	}
	
	protected PersistenceManager getPM() {
		return PMF.get().getPersistenceManager();
	}
	
	@Override
	protected void dispatch() {

	}

	@Override
	public void doStart() {
		if (checkSecurity()) {
			_pm = this.getPM();
			try {
				this.doExcute();
			} finally {
				_pm.close();
			}
		}
	}
	
	protected void doExcute() {
		this.dispatch();
	}
	
	protected boolean checkSecurity() {
		return true;
	}

}
